package org.rqb.panel;


import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.rqb.frame.ChatFrame;
import org.rqb.service.LANDevicesService;
import org.rqb.socket.MySocket;


import javax.swing.*;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Data
public class QueryLANDevicesPanel extends javax.swing.JPanel implements ActionListener {
    private JPanel parentPanel;
    private CardLayout cardLayout;
    private LANDevicesService lanDevicesService = new LANDevicesService(this);
    private String currentIp;
    private int threadNum = 25;
    private ExecutorService fixedThreadPool;

    private MySocket mySocket = MySocket.getInstance();

    private List<JButton> btnList = new ArrayList<>();
    private JPanel centerPanel;
    private InetAddress address;
    private JPanel northPanel;
    private JButton startBtn;
    private String lan;
    private JLabel currentIpLabel;


    private final Map<String,ChatFrame> chatFrameMap = new HashMap<>();

    public QueryLANDevicesPanel(JPanel parentPanel, CardLayout cardLayout) {
        this.parentPanel = parentPanel;
        this.cardLayout = cardLayout;
        this.currentIp = lanDevicesService.getCurrentIp();

        layoutInit();


        IpBtnsInit();

    }


    private void layoutInit() {
        this.setLayout(new BorderLayout());
        northPanel = new JPanel(new GridLayout(1,5));
        northPanel.add(new JLabel("当前局域网ip:"));
        currentIpLabel = new JLabel(currentIp);
        northPanel.add(currentIpLabel);

        startBtn = new JButton("开始");
        startBtn.addActionListener(this);
        northPanel.add(startBtn);
        this.add(northPanel, BorderLayout.NORTH);

        centerPanel = new JPanel();
        centerPanel.setLayout(new GridLayout(26,10));

        // 创建 JScrollPane 并将 centerPanel 添加到 JScrollPane 中
        JScrollPane scrollPane = new JScrollPane(centerPanel);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        JScrollBar verticalScrollBar = scrollPane.getVerticalScrollBar();
        //设置滚动条灵敏度 40
        verticalScrollBar.setUnitIncrement(40);
        //设置滚动条不可见
        verticalScrollBar.setPreferredSize(new Dimension(0,0));

        this.add(scrollPane, BorderLayout.CENTER);

    }

    private void IpBtnsInit() {
        //获取当前网段
        lan = getLan();
        btnList.clear();
        centerPanel.removeAll();
        for (int i = 1; i <= 255; i++) {
            JButton btn = new JButton(lan + "." + i);
            btn.setEnabled(false);
            btn.addActionListener(this);
            btnList.add(btn);
            centerPanel.add(btn);
        }





    }

    private String getLan() {
        try {
            InetAddress address = InetAddress.getByName(currentIp);
            String hostAddress = address.getHostAddress();
            return hostAddress.substring(0, hostAddress.lastIndexOf("."));

        } catch (UnknownHostException e) {
            log.error("传递过来的ip有误");
            return null;
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if (e.getSource() instanceof JButton) {
            JButton button = (JButton) e.getSource();
            if (button == startBtn) {  //开始按钮被点击
                log.info("开始按钮被点击");
                startBtnOnClick();
            } else { //点击的是ip按钮
                log.info("ip 按钮被点击");
                ipBtnOnClick(button.getText().trim(),currentIp);
            }




        }
    }

    private void ipBtnOnClick(String receiver,String sender) {
        ChatFrame chatFrame = chatFrameMap.get(receiver);
        if (chatFrame == null){
            chatFrame = new ChatFrame(sender, receiver);
            chatFrameMap.put(receiver,chatFrame);
        }
        //展示出来一个聊天对话框
        chatFrame.setVisible(true);

    }

    private void startBtnOnClick() {
        //先停止正在运行的线程
        if (fixedThreadPool != null){
            fixedThreadPool.shutdownNow();
        }
        //创建新线程池
        fixedThreadPool = Executors.newFixedThreadPool(threadNum);

        int start = 0;
        int end = 0;

        SwingUtilities.invokeLater(()->{
            //获取当前ip
            currentIp = lanDevicesService.getCurrentIp();

            //更新当前ip label
            currentIpLabel.setText(currentIp);
            //刷新ip按钮
            refreshIpBtn();

        });
        //  开启线程测试链接
        int num = 255 / threadNum;
        if (255 % threadNum != 0){
            num++;
        }
        for (int i = 0; i < threadNum; i++) {
            start = num * i + 1;
            end = num * (i + 1) > 255 ? 255 : num * (i + 1);
            fixedThreadPool.execute(new testLanDevicesThread(start, end));

        }








    }

    private void refreshIpBtn() {
        lan = getLan();
        for (int i = 1; i <= btnList.size(); i++) {
            final int currentIndex = i - 1;
//            SwingUtilities.invokeLater(()->{
//                JButton btn = btnList.get(currentIndex);
//                btn.setText(lan + "." + (currentIndex + 1));
//                btn.setEnabled(false);
//                btn.setBackground(Color.WHITE);
//            });
            JButton btn = btnList.get(currentIndex);
            btn.setText(lan + "." + (currentIndex + 1));
            btn.setEnabled(false);
            btn.setBackground(Color.WHITE);
        }

    }

    public void setBtnColor(String btnName, Color color) {
        ChatFrame chatFrame = chatFrameMap.get(btnName);
        if (chatFrame != null && !chatFrame.isVisible()) {   //表示当前聊天聊天界面没有显示，则改变按钮颜色
            JButton btn = btnList.get(Integer.parseInt(btnName.substring(btnName.lastIndexOf(".") + 1)) - 1);
            btn.setBackground(color);
        }
    }


    private class testLanDevicesThread extends Thread {
        private int start;
        private int end;

        public testLanDevicesThread(int start, int end) {
            this.start = start;
            this.end = end;
        }

        @Override
        public void run() {
            lanDevicesService.queryDevicesByInetAddress(lan,start,end);
        }
    }


    public void updateIpBtnBackground(int index, Color color){
        if (index < 0 || index > 254) {
            return;
        }
        //得到btn
        JButton btn = btnList.get(index);
        btn.setBackground(color);
        if (Color.RED == color){ //设置不可被点击
            btn.setEnabled(false);
        } else {
            btn.setEnabled(true);
        }

        validate();
        repaint();
    }





}
